package com.xnfh.field.ui.activity

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.widget.TextView
import androidx.core.view.get
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.UiSettings
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.GroundOverlay
import com.amap.api.maps.model.GroundOverlayOptions
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.Polygon
import com.amap.api.maps.model.PolygonOptions
import com.amap.api.maps.model.TileOverlayOptions
import com.amap.api.maps.model.TileProvider
import com.amap.api.maps.model.UrlTileProvider
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.xnfh.common.bean.FieldDetailBean
import com.xnfh.common.bean.TendencyYearBean
import com.xnfh.common.bean.UavImgBean
import com.xnfh.field.R
import com.xnfh.field.databinding.ActivityFieldTendencyImageBinding
import com.xnfh.field.ui.adapter.TendencyYearAdapter
import com.xnfh.field.ui.adapter.TendencyMonthAdapter
import com.xnfh.field.viewmodel.FieldTendencyImageViewModel
import com.xnfh.framework.base.BaseActivity
import com.xnfh.framework.base.BaseStateObserver
import com.xnfh.framework.utils.JsonUtlis
import com.xnfh.image.ImageUrl
import java.net.MalformedURLException
import java.net.URL

/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2023/12/1 11:33
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/12/1 11:33
 * @UpdateRemark: 更新说明
 */
class FieldTendencyImageActivity : BaseActivity<ActivityFieldTendencyImageBinding>() {
    override fun getLayoutID(): Int = R.layout.activity_field_tendency_image

    companion object {
        fun start(context: Context, bundle: Bundle? = null) {
            val intent = Intent(context, FieldTendencyImageActivity::class.java)
            if (bundle != null) {
                intent.putExtra("bundle", bundle)
            }
            context.startActivity(intent)
        }
    }

    private lateinit var viewModel: FieldTendencyImageViewModel
    private var aMap: AMap? = null
    private var polygon: Polygon? = null

    //覆盖物
    private var groundOverlay: GroundOverlay? = null
    private var uiSettings: UiSettings? = null
    private var yearAdapter: TendencyYearAdapter? = null
    private var monthAdapter: TendencyMonthAdapter? = null
    private var fieldDetailBean: FieldDetailBean? = null

    //无人机卫星图类型   3 遥感长势（卫星长势）  2无人机长势 1 无人机影像
    private var uavType = 3

    override fun init(savedInstanceState: Bundle?) {
        mBind.tendencyTitle.headerTitleTxt.text = getString(R.string.str_crop_tendency)
        val bundleExtra = Intent().getBundleExtra("bundle")
        fieldDetailBean = bundleExtra?.getSerializable("data") as FieldDetailBean
        initMapView(savedInstanceState)

        //设置recycleview管理器 -- start --
        val timeLayoutManager = LinearLayoutManager(this)
        timeLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
        mBind.tendencyYearRecycle.layoutManager = timeLayoutManager
        yearAdapter = TendencyYearAdapter()
        mBind.tendencyYearRecycle.adapter = yearAdapter
        mBind.tendencyMonthRecycle.layoutManager = LinearLayoutManager(this)
        monthAdapter = TendencyMonthAdapter()
        mBind.tendencyMonthRecycle.adapter = monthAdapter
        //设置recycleview管理器 -- end --

        //设置地图展示相关  -- start --
        setMapData()

        //设置年份、月份相关日期选择 -- start --
        setTimeSelect()

        //选择年份
        yearAdapter?.setOnItemSelectYearListener(object : TendencyYearAdapter.onItemSelectYear {
            override fun setSelect(position: Int) {
                viewModel.requestFieldDetailByYear(
                    fieldDetailBean?.fieldId,
                    (yearAdapter?.data?.get(position) as TendencyYearBean).year.toString()
                )
            }
        })
        //选择具体日期
        monthAdapter?.setOnItemSelectMonthistener(object : TendencyMonthAdapter.onItemSelectMonth {
            override fun setSelect(position: Int) {
                val uavImgBean = monthAdapter?.data?.get(position) as UavImgBean
                setCoverImage(uavImgBean.imageLng, uavImgBean.imageLat, uavImgBean.pathUrl)
            }
        })

        mBind.tendencyRadiogroup.setOnCheckedChangeListener { group, checkedId ->
            var monthList:List<UavImgBean>? = null
            when (group.checkedRadioButtonId) {
                mBind.tendencyWx.id -> {
                    //卫星长势
                    uavType = 3
                    monthList = fieldDetailBean?.remoteSensingList!!
                }

                mBind.tendencyWrj.id -> {
                    //无人机长势
                    uavType = 2
                    monthList = fieldDetailBean?.uavgrowthList!!
                }

                mBind.tendencyYx.id -> {
                    //无人机影像
                    uavType = 1
                    monthList = fieldDetailBean?.uavimageList!!
                }
            }
            if(monthList?.isNotEmpty() == true){
                monthList[0].selected = true
                setCoverImage(monthList[0].imageLng,monthList[0].imageLat,monthList[0].pathUrl)
                monthAdapter?.setNewInstance(monthList.toMutableList())
            }
        }
    }

    private fun setTimeSelect() {
        val years = fieldDetailBean?.year
        if (years.isNullOrEmpty()) {
            //设置空数据，顺便清空覆盖图
            yearAdapter?.setNewInstance(null)
            val textView = TextView(this)
            textView.text = getString(R.string.adapter_no_data)
            yearAdapter?.setEmptyView(textView)
            groundOverlay?.remove()
            return
        }
        //有数据就做展示
        val yearList = ArrayList<TendencyYearBean>()
        for (i in years.indices) {
            //设置默认选中第一条
            yearList.add(TendencyYearBean(years[i], i == 0))
        }
        //如果有数据，就正常展示数据。没有数据就使用年份的recycleview展示空数据提示
        yearAdapter?.setNewInstance(yearList)
        //设置默认的展示
        if (!fieldDetailBean?.remoteSensingList.isNullOrEmpty()) {
            fieldDetailBean?.remoteSensingList?.get(0)?.selected = true
            //设置覆盖图片
            setCoverImage(
                fieldDetailBean?.remoteSensingList?.get(0)?.imageLng,
                fieldDetailBean?.remoteSensingList?.get(0)?.imageLat,
                fieldDetailBean?.remoteSensingList?.get(0)?.pathUrl
            )
        }
        yearAdapter?.setNewInstance(yearList)
        monthAdapter?.setNewInstance(fieldDetailBean?.remoteSensingList?.toMutableList())
    }

    private fun setMapData() {
        try {
            //如果polygon不是空的，证明加载过，再次加载属于切换，所以要先清空
            if (polygon != null) {
                polygon?.remove()
            }
            val gpsList = JsonUtlis.toTwoArrayList(fieldDetailBean?.borderCoordinate)
            val builder = LatLngBounds.Builder()
            val latLngList = ArrayList<LatLng>()
            gpsList.forEach {
                val lon = it[0]
                val lat1 = it[1]
                val latlng = LatLng(lat1, lon)
                latLngList.add(latlng)
                builder.include(latlng)
            }
            latLngList.add(LatLng(gpsList[0][1], gpsList[0][0]))
            val polygonOpt =
                PolygonOptions().fillColor(0x4D3E9BFD).strokeColor(-0xbf6302).strokeWidth(10f)
            polygonOpt.zIndex(2f)
            polygon = aMap?.addPolygon(polygonOpt)
            polygon?.points = latLngList
            val bounds = builder.build()
            aMap?.animateCamera(CameraUpdateFactory.newLatLngBoundsRect(bounds, 450, 450, 250, 350))
            //因为覆盖物的添加是在请求成功之后  防止用户切换田块之后拿到的数据是空或者失败 还在显示上一个田块的覆盖物  所以在这也做下清除
            if (groundOverlay != null) {
                groundOverlay?.remove()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun setCoverImage(imageLng: String?, imageLat: String?, imageUrl: String?) {
        if (imageLng == null || imageLat == null || imageUrl == null) return
        //处理lng
        val imageLngReplace = imageLng.replace("[", "").replace("]", "")
        val imageLngSplit = imageLngReplace.split(",")
        if (imageLngSplit.size != 2) return
        val lng = imageLngSplit[0].toDouble()
        val lat = imageLngSplit[1].toDouble()
        val latLng = LatLng(lat, lng)
        //处理lat
        val imageLatReplace = imageLat.replace("[", "").replace("]", "")
        val imageLatSplit = imageLatReplace.split(",")
        if (imageLatSplit.size != 2) return
        val lng1 = imageLatSplit[0].toDouble()
        val lat1 = imageLatSplit[1].toDouble()
        val latLng1 = LatLng(lat1, lng1)
        val options = RequestOptions().override(200, 100)
        Glide.with(this).asBitmap().load(ImageUrl.BASEURL + imageUrl).apply(options)
            .into(object : CustomTarget<Bitmap>() {
                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    if (groundOverlay != null) groundOverlay?.remove()
                    val bounds = LatLngBounds.Builder().include(latLng).include(latLng1).build()
                    groundOverlay = aMap!!.addGroundOverlay(
                        GroundOverlayOptions()
                            .anchor(0.5f, 0.5f)
                            .transparency(0.1f)
                            .zIndex(10f)
                            .image(BitmapDescriptorFactory.fromBitmap(resource))
                            .positionFromBounds(bounds)
                    )
                }

                override fun onLoadCleared(placeholder: Drawable?) {
                }

            })
    }

    override fun observe() {
        viewModel = FieldTendencyImageViewModel()
        viewModel.fieldDetailData.observe(this, object : BaseStateObserver<FieldDetailBean>(null) {
            override fun getRespDataSuccess(it: FieldDetailBean) {
                super.getRespDataSuccess(it)
                fieldDetailBean = it
                val uavImgBeanS = when (uavType) {
                    1 -> {
                        it.uavimageList
                    }

                    2 -> {
                        it.uavgrowthList
                    }

                    else -> {
                        it.remoteSensingList
                    }
                }
                if (uavImgBeanS.isNotEmpty()) {
                    uavImgBeanS[0].selected = true
                    setCoverImage(
                        uavImgBeanS[0].imageLng,
                        uavImgBeanS[0].imageLat,
                        uavImgBeanS[0].pathUrl
                    )
                }
                monthAdapter?.setNewInstance(uavImgBeanS.toMutableList())
            }
        })
    }

    fun initMapView(savedInstanceState: Bundle?) {
        mBind.tendencyMapview.onCreate(savedInstanceState)
        if (aMap == null) {
            aMap = mBind.tendencyMapview.map
        }
        aMap?.mapType = AMap.MAP_TYPE_NORMAL
        aMap?.showMapText(false)
        uiSettings = aMap?.uiSettings
        uiSettings?.isScaleControlsEnabled = true
        uiSettings?.isTiltGesturesEnabled = false
        uiSettings?.isZoomControlsEnabled = false
        uiSettings?.isRotateGesturesEnabled = false
        aMap?.maxZoomLevel = 18f

        val url =
            "http://t0.tianditu.gov.cn/DataServer?T=img_w&tk=42713dd342d128b5e5f8a9bdad589c7c&x=%d&y=%d&l=%d&s=Galile"
        val tileProvider: TileProvider = object : UrlTileProvider(256, 256) {
            override fun getTileUrl(x: Int, y: Int, zoom: Int): URL? {
                try {
                    return URL(String.format(url, x, y, zoom))
                } catch (e: MalformedURLException) {
                    e.printStackTrace()
                }
                return null
            }
        }
        if (tileProvider != null) {
            aMap?.addTileOverlay(
                TileOverlayOptions()
                    .tileProvider(tileProvider)
                    .diskCacheEnabled(false)
                    .diskCacheDir("/storage/emulated/0/amap/cache")
                    .diskCacheSize(100000)
                    .memoryCacheEnabled(false)
                    .memCacheSize(100000)
            )
        }
        val url2 =
            "http://t0.tianditu.gov.cn/DataServer?T=cia_w&tk=42713dd342d128b5e5f8a9bdad589c7c&x=%d&y=%d&l=%d&s=Galile"
        val tileProvider2: TileProvider = object : UrlTileProvider(256, 256) {
            override fun getTileUrl(x: Int, y: Int, zoom: Int): URL? {
                try {
                    return URL(String.format(url2, x, y, zoom))
                } catch (e: MalformedURLException) {
                    e.printStackTrace()
                }
                return null
            }
        }
        if (tileProvider != null) {
            aMap?.addTileOverlay(
                TileOverlayOptions()
                    .tileProvider(tileProvider2)
                    .diskCacheEnabled(false)
                    .diskCacheDir("/storage/emulated/0/amap/cache")
                    .diskCacheSize(100000)
                    .memoryCacheEnabled(false)
                    .memCacheSize(100000)
            )
        }
    }

}